package com.kifas.controller;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.kifas.entity.GroupEntity;
import com.kifas.model.xml.GroupModel;
import com.kifas.model.xml.PersistStatus;
import com.kifas.service.EntityServiceManager;

@Component
@Scope("prototype")
@Path("/Groups")
public class GroupController {

	private static Logger log = Logger.getLogger(GroupController.class);

	@Context
	UriInfo uriInfo;

	@Autowired
	private EntityServiceManager entityManager;
	
	@GET
	@Produces(MediaType.APPLICATION_XML)
	public List<GroupModel> getGroups(){
		return transformList(entityManager.getGroups());
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus insert(JAXBElement<GroupModel> xml) {
		GroupModel model = xml.getValue();
		GroupEntity group = new GroupEntity(model.getIdGroup(), model.getName(), model.isEnable());
		try {
			entityManager.persist(group);
		} catch (Exception e) {
			log.error("can not persist Group Entity", e);
			return new PersistStatus("GroupEntity", "failed", "can not persist Group Entity");
		}
		
		return new PersistStatus("GroupEnitty", "success");
	}
	
	@GET
	@Path("{id}")
	@Produces(MediaType.APPLICATION_XML)
	public GroupModel getGroup(@PathParam("id") Long idGroup) {
		return transform(entityManager.getGroupById(idGroup));
	}
	
	private List<GroupModel> transformList(List<GroupEntity> groups) {
		List<GroupModel> models = new ArrayList<GroupModel>();
		for(GroupEntity group : groups){
			models.add(transform(group));
		}
		return models;
	}

	private GroupModel transform(GroupEntity group) {
		return new GroupModel(group.getIdGroup(), group.getName(), group.isEnable());
	}
}
